package li.kaeppe.travel.tracker.parser.gpx;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;

import javax.xml.bind.JAXBElement;
import javax.xml.transform.stream.StreamSource;

import li.kaeppe.travel.tracker.domain.WayPoint;
import li.kaeppe.travel.tracker.parser.LevelAsserter;
import li.kaeppe.travel.tracker.parser.NoTimeStampException;
import li.kaeppe.travel.tracker.parser.ParseException;
import li.kaeppe.travel.tracker.parser.WayPointParser;
import li.kaeppe.travel.tracker.parser.gpx.integration.GpxType;
import li.kaeppe.travel.tracker.parser.gpx.integration.TrkType;
import li.kaeppe.travel.tracker.parser.gpx.integration.TrksegType;
import li.kaeppe.travel.tracker.parser.gpx.integration.WptType;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.XmlMappingException;

public class GpxWayPointParser implements WayPointParser {

	/* **************************************************** */
	/*                      CONSTANTS                       */
	/* **************************************************** */
	
	private static final Log log = LogFactory.getLog(GpxWayPointParser.class);
	
	/* **************************************************** */
	/*                     MEMBER FIELDS                    */
	/* **************************************************** */

	private Unmarshaller unmarshaller;
	
	private String description;
	
	private long interval = 20*1000;
	
	private LevelAsserter levelAsserter;
	
	/* **************************************************** */
	/*                      CONSTRUCTOR                     */
	/* **************************************************** */

	/* **************************************************** */
	/*                    PUBLIC METHODS                    */
	/* **************************************************** */
	
	public Collection<WayPoint> parse(InputStream in) 
		throws ParseException, XmlMappingException, IOException, NoTimeStampException {
		return this.parse(in, null);
	}

	
	public Collection<WayPoint> parse(InputStream in, Date startDate)
		throws ParseException, XmlMappingException, IOException, NoTimeStampException {
		GpxType gpxTrack = null;

		@SuppressWarnings("unchecked")
		JAXBElement<GpxType> object = (JAXBElement<GpxType>) this.getUnmarshaller().unmarshal(new StreamSource(in));
		gpxTrack = object.getValue();
		Collection<WayPoint> points = new ArrayList<WayPoint>();
		
		Integer counter = 1;
		WayPoint wp = null;
		Date date = startDate;
		boolean isFirstWayPoint = true;
		
		for(TrkType track : gpxTrack.getTrk()) {
			for(TrksegType seg : track.getTrkseg()) {
				for(WptType point : seg.getTrkpt()) {
					if(log.isDebugEnabled()) {
						log.debug(point.getTime() + ": Point [" + point.getLon() + "," + point.getLat() + "]");
					}
					if ( (date == null) && (point.getTime() == null) ) {
						throw new NoTimeStampException();
					}
					else if (point.getTime() == null) {
						date = this.incrementDate(date);
					} else {
						date = point.getTime().toGregorianCalendar().getTime();
					}
					wp = new WayPoint(point.getLon(), 
							 point.getLat(),
							 date,
							 point.getEle());
					points.add(wp);
					
					if(isFirstWayPoint == true) {
						wp.setLevel(this.getLevelAsserter().getFirstPointLevel());
						isFirstWayPoint = false;
					} else {
						wp.setLevel(this.getLevelAsserter().getLevel(counter));
					}
					
					counter++;
				}
			}
		}
		// the last entry shall also be visible for low detail maps
		wp.setLevel(this.getLevelAsserter().getLastPointLevel(counter));
		return points;
	}

	/* **************************************************** */
	/*                  PROTECTED METHODS                   */
	/* **************************************************** */

	/* **************************************************** */
	/*               PACKAGE PRIVATE METHODS                */
	/* **************************************************** */
		
	/* **************************************************** */
	/*                   PRIVATE METHODS                    */
	/* **************************************************** */
	
	private Date incrementDate(Date date) {
		return new Date(date.getTime() + this.getInterval());
	}

	/* **************************************************** */
	/*                  GETTERS AND SETTERS                 */
	/* **************************************************** */
	
	public Unmarshaller getUnmarshaller() {
		return unmarshaller;
	}

	public void setUnmarshaller(Unmarshaller unmarshaller) {
		this.unmarshaller = unmarshaller;
	}
	
	public long getInterval() {
		return interval;
	}

	public void setInterval(long interval) {
		this.interval = interval;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}


	public LevelAsserter getLevelAsserter() {
		return levelAsserter;
	}


	public void setLevelAsserter(LevelAsserter levelAsserter) {
		this.levelAsserter = levelAsserter;
	}
}
